import EnemyControl from "./EnemyControl";

const {ccclass, property} = cc._decorator;

@ccclass
export default class PlayerControll extends cc.Component {

    @property(cc.Prefab)
    private bulletPrefab: cc.Prefab = null;

    @property(cc.Prefab)
    private enemyPrefab: cc.Prefab = null;

    private bulletTimer = null;

    private enemyTimer = null;

    start() {
        // 开启碰撞检测
        cc.director.getCollisionManager().enabled = true;

        this.node.on(cc.Node.EventType.TOUCH_MOVE, (event) => {
            this.node.setPosition(event.getLocation());
        });
        this.bulletTimer = setInterval(() => {
            // 创建子弹
            let bullet = cc.instantiate(this.bulletPrefab);
            // 设置父物体
            bullet.setParent(cc.director.getScene());
            // 设置子弹位置
            bullet.x = this.node.x;
            bullet.y = this.node.y + 60;
        }, 500);

        this.enemyTimer = setInterval(() => {
            // 计时器
            let aNumber: number = 425 * Math.random() + 1;
            let xPos: number = Math.floor(aNumber);

            let enemy = cc.instantiate(this.enemyPrefab);
            enemy.setParent(cc.director.getScene());
            enemy.setPosition(xPos, 750);
        }, 1000);
    }

    update(dt) {

    }

    onCollisionEnter(other, self) {
        if (other.tag == 1) {
            cc.loader.loadRes('hero1_die', cc.SpriteFrame, (err, res) => {
                this.node.getComponent(cc.Sprite).spriteFrame = res;
            })
            // 300毫秒后销毁
            setTimeout(() => {
                this.node.destroy();
            }, 300);
            clearInterval(this.bulletTimer);
            clearInterval(this.enemyTimer);
        }
    }
}
